#include "imageviewerdialog.h"
#include "models/command.h"
#include <QKeyEvent>
#include <QScreen>
#include <QApplication>
#include <QFileInfo>


ImageViewerDialog::ImageViewerDialog(const QString& imagePath, QWidget* parent)
    : PopupDialog(parent)
{
    setGeometry(parentWidget()->geometry());
    // 创建布局
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setContentsMargins(int(20*g_xScale), int(20*g_yScale), int(20*g_xScale), int(30*g_yScale));
    layout->setSpacing(0);
    
    // 创建顶部工具栏
    QWidget* topBar = new QWidget(this);
    topBar->setStyleSheet("background-color: transparent;");
    QHBoxLayout* topLayout = new QHBoxLayout(topBar);
    
    // 创建图片名称标签
    QFileInfo fileInfo(imagePath);
    QLabel* nameLabel = new QLabel(fileInfo.fileName(), this);
    nameLabel->setStyleSheet(QString("color: white; font-family: '微软雅黑'; font-size: %1px;").arg(int(20*g_xScale)));
    
    // 创建关闭按钮
    m_closeButton = new TouchButton(this);
    m_closeButton->setFixedSize(int(40*g_xScale), int(40*g_xScale));
    m_closeButton->setStyleSheet(
        "QPushButton{ \
            border-image: url(:/images/close.png); \
            background-color:transparent; \
        } \
        QPushButton:pressed{ \
            background-color: rgb(255, 0, 0); \
        }"
    );
    connect(m_closeButton, &QPushButton::clicked, this, &QDialog::accept);

    topLayout->setContentsMargins(0, 0, 0, 0);
    topLayout->setSpacing(0);
    // 添加到顶部布局
    topLayout->addWidget(nameLabel);
    topLayout->addStretch();
    topLayout->addWidget(m_closeButton);
    
    // 创建图片标签
    m_imageLabel = new QLabel(this);
    m_imageLabel->setAlignment(Qt::AlignCenter);
    m_imageLabel->setStyleSheet("background-color: black;");
    
    // 加载并显示图片
    QPixmap pixmap(imagePath);
    if (!pixmap.isNull()) {
        // 计算缩放后的大小，保持宽高比，使用窗口大小的90%
        QSize scaledSize = pixmap.size();
        scaledSize.scale(QSize(width() - int(40*g_xScale), height()-int(100*g_yScale)), Qt::KeepAspectRatio);
        
        // 设置缩放后的图片
        m_imageLabel->setPixmap(pixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    }
    
    // 设置对话框背景
    setStyleSheet("background-color: rgba(0, 0, 0, 200);");
    
    // 添加部件到布局
    layout->addWidget(topBar);
    layout->addWidget(m_imageLabel, 1);  // 添加拉伸因子，使图片标签占据所有可用空间
}

void ImageViewerDialog::keyPressEvent(QKeyEvent* event)
{
    // ESC键关闭窗口
    if (event->key() == Qt::Key_Escape) {
        accept();
    }
    QDialog::keyPressEvent(event);
} 
